package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.LoginMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    /**
     *
     * @param username  就是当前登录信息的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, username));
        if(login != null){
            //根据用户id去查询自己的权限信息
            List<Permission> permissions = loginMapper.selectPermissionByLoginId(login.getId());
            //构建权限信息
            List<SimpleGrantedAuthority> auth = permissions.stream().map(permission ->
                    new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
            String password = login.getPassword();
            login.setPassword(null);
            return new User(JSON.toJSONString(login),password,auth);//账号  密码 权限
        }
        return null;
    }
}
